package sync;
// 1. 懒汉式 - 线程不安全
// 优点：延迟加载，节省内存
// 缺点：线程不安全，多线程环境下可能创建多个实例
class Singleton1 {
    private static Singleton1 instance;
    private Singleton1() {}
    public static Singleton1 getInstance() {
        if (instance == null) {
            instance = new Singleton1();
        }
        return instance;
    }
}

// 2. 懒汉式 - 线程安全（同步方法）
// 优点：线程安全，延迟加载
// 缺点：synchronized导致性能开销大
class Singleton2 {
    private static Singleton2 instance;
    private Singleton2() {}
    public static synchronized Singleton2 getInstance() {
        if (instance == null) {
            instance = new Singleton2();
        }
        return instance;
    }
}

// 3. 双重检查锁定（Double-Checked Locking）
// 优点：线程安全，延迟加载，性能较好
// 缺点：实现较复杂，需要volatile关键字
class Singleton3 {
    private static volatile Singleton3 instance;
    private Singleton3() {}
    public static Singleton3 getInstance() {
        if (instance == null) {
            synchronized (Singleton3.class) {
                if (instance == null) {
                    instance = new Singleton3();
                }
            }
        }
        return instance;
    }
}

// 4. 静态内部类
// 优点：线程安全，延迟加载，实现简单
// 缺点：无法传参
class Singleton4 {
    private Singleton4() {}
    private static class SingletonHolder {
        private static final Singleton4 INSTANCE = new Singleton4();
    }
    public static Singleton4 getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

// 5. 饿汉式
// 优点：线程安全，实现简单
// 缺点：不是延迟加载，可能造成内存浪费
class Singleton5 {
    private static final Singleton5 instance = new Singleton5();
    private Singleton5() {}
    public static Singleton5 getInstance() {
        return instance;
    }
}

// 6. 枚举方式
// 优点：最简单，自动支持序列化，绝对防止多次实例化
// 缺点：不是延迟加载
enum Singleton6 {
    INSTANCE;
    public void doSomething() {
        // 业务方法
    }
}

